package com.vision.sales.sv.serv;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.vision.core.sv.util.CollectionUtils;
import com.vision.sales.sv.report.ReportParams;

public class SalesParams extends ReportParams {

	static final DateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
	
	String title;
	String type;
	int year;
	List<Integer> months;
	List<Long> companyIds;
	List<Long> customerIds;
	StringBuffer warnings = new StringBuffer();
	
	public SalesParams(HttpServletRequest req) {
		title = req.getParameter("title");
		title = title == null ? "" : title.trim();
		if (title.isEmpty())
			title = "Product Sales Report";
		
		type = req.getParameter("type");
		if (!ReportConstants.MONTHLY.equalsIgnoreCase(type) 
				&& !ReportConstants.ANNUAL.equalsIgnoreCase(type)) {
			warnings.append("Type cannot be determined. Defaulting to annual.\n");
			type = ReportConstants.ANNUAL;
		}
		
		Calendar now = Calendar.getInstance();
		
		try {
			year = Integer.parseInt(req.getParameter("year"));
		} catch (Exception e) {
			year = now.get(Calendar.YEAR);
			warnings.append("Failed to parse year: " + req.getParameter("year") + ". Using current year: " + year + "\n");
		}
		
		String sMonths = req.getParameter("months");
		if (sMonths != null)
			months = CollectionUtils.intsFromString(sMonths, ',');
		if (months == null || months.isEmpty()) {
			int mo = now.get(Calendar.MONTH) + 1;
			warnings.append("Month is empty. Using current month: " + mo + "\n");
			months = new ArrayList<Integer>();
			months.add(mo);
		}
		Collections.sort(months);
		
		String sCompanyIds = req.getParameter("companies");
		if (sCompanyIds != null)
			companyIds = CollectionUtils.longsFromString(sCompanyIds, ',');
		
		String sCustomerIds = req.getParameter("customers");
		if (sCustomerIds != null)
			customerIds = CollectionUtils.longsFromString(sCustomerIds, ',');
	}
	
	public boolean isAnnual() {
		return ReportConstants.ANNUAL.equalsIgnoreCase(type);
	}
	
	public String getWarnings()
	{
		return warnings.toString();
	}
	
}